<html>
<head>
    <meta charset="UTF-8">
    <title>编辑文章</title>
</head>
<body>
    <h1>编辑博客文章</h1>
    <form id="edit-form">
        <input type="hidden" name="slug" value="{{ slug }}">
        <p>标题: <input type="text" name="title" value="{{ title }}" required></p>
        <p>正文:<br><textarea name="content" rows="10" cols="50">{{ content }}</textarea></p>
        <p>
            <label>
                <input type="checkbox" name="published" {% if published == "true" %}checked{% endif %}> 发布
            </label>
        </p>
        <p><button type="submit">保存</button></p>
    </form>
    <p><a href="/admin">返回后台</a></p>

    <script>
        document.getElementById("edit-form").addEventListener("submit", async (event) => {
            event.preventDefault();

            const form = event.target;
            const data = {
                title: form.title.value,
                slug: form.slug.value,
                content: form.content.value,
                published: form.published.checked
            };

            const response = await fetch("/admin/edit/" + data.slug, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(data)
            });

            if (response.redirected) {
                window.location.href = response.url;
            } else {
                alert("保存失败");
            }
        });
    </script>
</body>
</html>
